package com.wlit.ui;

import com.alibaba.fastjson.JSONObject;
import com.wlit.tianping.TianpingConstant;
import com.wlit.tianping.TianpingService;
import org.apache.log4j.Logger;
import org.cef.browser.CefBrowser;
import org.cef.browser.CefFrame;
import org.cef.callback.CefQueryCallback;
import org.cef.handler.CefMessageRouterHandler;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.wlit.tianping.TianpingConstant.ERROR_CODE;
import static com.wlit.tianping.TianpingConstant.SUCCESS_CODE;


/**
 * 天平的交互数据
 */
public class TianpingDataHandler implements CefMessageRouterHandler {

    private Logger logger = Logger.getLogger(TianpingDataHandler.class);

    @Override
    public boolean onQuery(CefBrowser cefBrowser, CefFrame cefFrame, long l, String s, boolean b, CefQueryCallback callback) {
        logger.info("onQuery:" + s);
        if ("getWeight".equals(s)) {
            TianpingService tianpingService = TianpingService.getInstance();
            boolean isSend = tianpingService.sendData(TianpingConstant.WEIGHT_CMD);
            JSONObject jsonObject = new JSONObject();
            if (isSend) {
                CompletableFuture<String> future = tianpingService.getData();
                try {
                    String result = future.get(10, TimeUnit.SECONDS);
                    if (result != null) {
                        jsonObject.fluentPut("code", SUCCESS_CODE).fluentPut("message", "OK").fluentPut("data", result);
                    } else {
                        jsonObject.fluentPut("code", ERROR_CODE).fluentPut("message", "天平读取超时");
                    }
                } catch (Exception e) {
                    jsonObject.fluentPut("code", ERROR_CODE).fluentPut("message", e.getMessage());
                    logger.error("查询称重结果出错"+e);
                }
            }else {
                jsonObject.fluentPut("code", ERROR_CODE).fluentPut("message", "天平未连接");
            }
            callback.success(jsonObject.toJSONString());
        }else if ("getStatus".equals(s)){
            JSONObject jsonObject = new JSONObject();
            boolean isOpen = TianpingService.getInstance().isOpen();
            jsonObject.put("code",isOpen ? SUCCESS_CODE:ERROR_CODE);
            jsonObject.put("message",isOpen ? "open":"close");
            callback.success(jsonObject.toJSONString());
        }
        return true;
    }

    @Override
    public void onQueryCanceled(CefBrowser cefBrowser, CefFrame cefFrame, long l) {
        logger.info("onQueryCanceled:" + l);
    }

    @Override
    public void setNativeRef(String s, long l) {
        logger.info("setNativeRef:" + s + ":" + l);
    }

    @Override
    public long getNativeRef(String s) {
        logger.info("getNativeRef:" + s);
        return 0;
    }


}
